package com.roncoo.education.course.service.api.biz;

import javax.validation.constraints.NotNull;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.roncoo.education.common.core.base.Page;
import com.roncoo.education.common.core.base.Result;
import com.roncoo.education.common.core.enums.StatusIdEnum;
import com.roncoo.education.common.elasticsearch.EsExperiment;
import com.roncoo.education.common.elasticsearch.EsPageUtil;
import com.roncoo.education.common.service.BaseBiz;
import com.roncoo.education.course.dao.ExperimentDao;
import com.roncoo.education.course.service.api.req.ApiExperimentPageReq;
import com.roncoo.education.course.service.api.resp.ApiExperimentPageResp;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;

/**
 * API-实验信息
 *
 * @author wujing
 */
@Component
@RequiredArgsConstructor
public class ApiExperimentBiz extends BaseBiz {

    @NotNull
    private final ExperimentDao dao;

    @NotNull
    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    public Result<Page<ApiExperimentPageResp>> searchForPage(ApiExperimentPageReq req) {
        NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder();
        // 高亮字段
        nsb.withHighlightFields(new HighlightBuilder.Field("mingcheng").preTags("<mark>").postTags("</mark>"));

        // 分页
        nsb.withPageable(PageRequest.of(req.getPageCurrent() - 1, req.getPageSize()));

        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        // 过滤状态
        qb.must(QueryBuilders.termQuery("statusId", StatusIdEnum.YES.getCode()));
        if (ObjectUtil.isNotEmpty(req.getZhuanye())) {
            qb.must(QueryBuilders.termQuery("zhuanye" + ".keyword", req.getZhuanye()));
//            qb.must(QueryBuilders.termQuery("categoryId", 0));
        }
        if (ObjectUtil.isNotEmpty(req.getKechengjibie())) {
            qb.must(QueryBuilders.termQuery("kechengjibie" + ".keyword", req.getKechengjibie()));
        }
        if (ObjectUtil.isNotEmpty(req.getKechengleixing())) {
            qb.must(QueryBuilders.termQuery("kechengleixing" + ".keyword", req.getKechengleixing()));
        }
        if (ObjectUtil.isNotEmpty(req.getShiyanleixing())) {
            qb.must(QueryBuilders.termQuery("shiyanleixing" + ".keyword", req.getShiyanleixing()));
        }        
        if (StringUtils.hasText(req.getMingcheng())) {
            // 模糊查询multiMatchQuery，最佳字段best_fields
            qb.must(QueryBuilders.multiMatchQuery(req.getMingcheng(), "mingcheng").type(MultiMatchQueryBuilder.Type.BEST_FIELDS));
        } else {
            // 课程排序（sort）
            nsb.withSort(new FieldSortBuilder("experimentSort").order(SortOrder.ASC));
            nsb.withSort(new FieldSortBuilder("id").order(SortOrder.DESC));
        }
        nsb.withQuery(qb);

        SearchHits<EsExperiment> searchHits = elasticsearchRestTemplate.search(nsb.build(), EsExperiment.class, IndexCoordinates.of(EsExperiment.EXPERIMENT));
        return Result.success(EsPageUtil.transform(searchHits, req.getPageCurrent(), req.getPageSize(), ApiExperimentPageResp.class));
    }
}
